<!DOCTYPE html>
<html lang=zh-CN>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta property="og:description" content="samuel-24276的博客">
    <meta property="og:type" content="website">
    <meta name="description" content="samuel-24276的博客">
    <meta name="keyword"  content="aircloud">
    <link rel="shortcut icon" href="/myblog/img/favicon.ico">

    <title>
        
        JavaScript学习日记（4） - samuel-24276的博客 | samuel-24276&#39;s Blog
        
    </title>

    <!-- Custom CSS -->
    
<link rel="stylesheet" href="/myblog/css/aircloud.css">

    
<link rel="stylesheet" href="/myblog/css/gitment.css">

    <!--<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">-->
    <link href="//at.alicdn.com/t/font_620856_28hi1hpxx24.css" rel="stylesheet" type="text/css">
    <!-- ga & ba script hoook -->
    <script></script>
<meta name="generator" content="Hexo 7.1.1"></head>

<body>

<div class="site-nav-toggle" id="site-nav-toggle">
    <button>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
    </button>
</div>

<div class="index-about">
    <i> Like what you do, do what you like </i>
</div>

<div class="index-container">
    
    <div class="index-left">
        
<div class="nav" id="nav">
    <div class="avatar-name">
        <div class="avatar ">
            <img src="/myblog/img/avatar.jpg" />
        </div>
        <div class="name">
            <i>samuel-24276</i>
        </div>
    </div>
    <div class="contents" id="nav-content">
        <ul>
            <li >
                <a href="/myblog/">
                    <i class="iconfont icon-shouye1"></i>
                    <span>主页</span>
                </a>
            </li>
            <li >
                <a href="/myblog/tags">
                    <i class="iconfont icon-biaoqian1"></i>
                    <span>标签</span>
                </a>
            </li>
            <li >
                <a href="/myblog/archives">
                    <i class="iconfont icon-guidang2"></i>
                    <span>存档</span>
                </a>
            </li>
            <li >
                <a href="/myblog/collect/">
                    <i class="iconfont icon-shoucang1"></i>
                    <span>收藏</span>
                </a>
            </li>
            <li >
                <a href="/myblog/about/">
                    <i class="iconfont icon-guanyu2"></i>
                    <span>关于</span>
                </a>
            </li>
            
            <li>
                <a id="search">
                    <i class="iconfont icon-sousuo1"></i>
                    <span>搜索</span>
                </a>
            </li>
            
        </ul>
    </div>
    
        <div id="toc" class="toc-article">
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-Promise"><span class="toc-text">使用 Promise</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BA%A6%E5%AE%9A"><span class="toc-text">约定</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8"><span class="toc-text">链式调用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Catch%E7%9A%84%E5%90%8E%E7%BB%AD%E9%93%BE%E5%BC%8F%E6%93%8D%E4%BD%9C"><span class="toc-text">Catch的后续链式操作</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%94%99%E8%AF%AF%E4%BC%A0%E9%80%92-notebook"><span class="toc-text">错误传递:notebook:</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E6%8B%92%E7%BB%9D%E4%BA%8B%E4%BB%B6"><span class="toc-text">Promise 拒绝事件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9C%A8%E6%97%A7%E5%BC%8F%E5%9B%9E%E8%B0%83-API-%E4%B8%AD%E5%88%9B%E5%BB%BA-Promise"><span class="toc-text">在旧式回调 API 中创建 Promise</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%84%E5%90%88-notebook"><span class="toc-text">组合:notebook:</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%97%B6%E5%BA%8F-notebook"><span class="toc-text">时序:notebook:</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B5%8C%E5%A5%97-notebook"><span class="toc-text">嵌套:notebook:</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B8%B8%E8%A7%81%E9%94%99%E8%AF%AF"><span class="toc-text">常见错误</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E8%A7%81"><span class="toc-text">参见</span></a></li></ol></li></ol>
</div>
    
</div>


<div class="search-field" id="search-field">
    <div class="search-bg" id="search-bg"></div>
    <div class="search-container">
        <div class="search-input">
            <span id="esc-search"> <i class="icon-fanhui iconfont"></i></span>
            <input id="search-input"/>
            <span id="begin-search">搜索</span>
        </div>
        <div class="search-result-container" id="search-result-container">

        </div>
    </div>
</div>

        <div class="index-about-mobile">
            <i> Like what you do, do what you like </i>
        </div>
    </div>
    
    <div class="index-middle">
        <!-- Main Content -->
        


<div class="post-container">
    <div class="post-title">
        JavaScript学习日记（4）
    </div>

    <div class="post-meta">
        <span class="attr">发布于：<span>2023-05-14 16:14:28</span></span>
        
        <span class="attr">标签：/
        
        <a class="tag" href="/myblog/tags/#前端" title="前端">前端</a>
        <span>/</span>
        
        <a class="tag" href="/myblog/tags/#JS" title="JS">JS</a>
        <span>/</span>
        
        
        </span>
        <span class="attr">访问：<span id="busuanzi_value_page_pv"></span>
</span>
</span>
    </div>
    <div class="post-content no-indent">
        <h1 id="使用-Promise"><a href="#使用-Promise" class="headerlink" title="使用 Promise"></a>使用 Promise</h1><p><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise"><code>Promise</code></a> 是一个对象，它代表了一个异步操作的最终完成或者失败。因为大多数人仅仅是使用已创建的 Promise 实例对象，所以本教程将首先说明怎样使用 Promise，再说明如何创建 Promise。</p>
<p>本质上 Promise 是一个函数返回的对象，我们可以在它上面绑定回调函数，这样我们就不需要在一开始把回调函数作为参数传入这个函数了。</p>
<p>假设现在有一个名为 <code>createAudioFileAsync()</code> 的函数，它接收一些配置和两个回调函数，然后异步地生成音频文件。一个回调函数在文件成功创建时被调用，另一个则在出现异常时被调用。</p>
<p>以下为使用 <code>createAudioFileAsync()</code> 的示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 成功的回调函数</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">successCallback</span>(<span class="params">result</span>) &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;音频文件创建成功：&quot;</span> + result);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 失败的回调函数</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">failureCallback</span>(<span class="params">error</span>) &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;音频文件创建失败：&quot;</span> + error);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="title function_">createAudioFileAsync</span>(audioSettings, successCallback, failureCallback)</span><br></pre></td></tr></table></figure>

<p>更现代的函数会返回一个 Promise 对象，使得你可以将你的回调函数绑定在该 Promise 上。</p>
<p>如果函数 <code>createAudioFileAsync()</code> 被重写为返回 Promise 的形式，那么我们可以像下面这样简单地调用它：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> promise = <span class="title function_">createAudioFileAsync</span>(audioSettings);</span><br><span class="line">promise.<span class="title function_">then</span>(successCallback, failureCallback);</span><br></pre></td></tr></table></figure>

<p>或者简写为：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">createAudioFileAsync</span>(audioSettings).<span class="title function_">then</span>(successCallback, failureCallback);</span><br></pre></td></tr></table></figure>

<p>我们把这个称为 <em>异步函数调用</em>，这种形式有若干优点，下面我们将会逐一讨论。</p>
<h2 id="约定"><a href="#约定" class="headerlink" title="约定"></a>约定</h2><p>不同于“老式”的传入回调，在使用 Promise 时，会有以下约定：</p>
<ul>
<li>在本轮 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Event_loop#%E6%89%A7%E8%A1%8C%E8%87%B3%E5%AE%8C%E6%88%90">事件循环</a> 运行完成之前，回调函数是不会被调用的。</li>
<li>即使异步操作已经完成（成功或失败），在这之后通过 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/then"><code>then()</code></a> 添加的回调函数也会被调用。</li>
<li>通过多次调用 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/then"><code>then()</code></a> 可以添加多个回调函数，它们会按照插入顺序进行执行。</li>
</ul>
<p>Promise 很棒的一点就是<strong>链式调用</strong>（<strong>chaining</strong>）。</p>
<h2 id="链式调用"><a href="#链式调用" class="headerlink" title="链式调用"></a>链式调用</h2><p>连续执行两个或者多个异步操作是一个常见的需求，在上一个操作执行成功之后，开始下一个的操作，并带着上一步操作所返回的结果。我们可以通过创造一个 <strong>Promise 链</strong>来实现这种需求。</p>
<p>见证奇迹的时刻：<code>then()</code> 函数会返回一个和原来不同的<strong>新的 Promise</strong>：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> promise = <span class="title function_">doSomething</span>();</span><br><span class="line"><span class="keyword">const</span> promise2 = promise.<span class="title function_">then</span>(successCallback, failureCallback);</span><br></pre></td></tr></table></figure>

<p>或者</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> promise2 = <span class="title function_">doSomething</span>().<span class="title function_">then</span>(successCallback, failureCallback);</span><br></pre></td></tr></table></figure>

<p><code>promise2</code> 不仅表示 <code>doSomething()</code> 函数的完成，也代表了你传入的 <code>successCallback</code> 或者 <code>failureCallback</code> 的完成，这两个函数也可以返回一个 Promise 对象，从而形成另一个异步操作，这样的话，在 <code>promise2</code> 上新增的回调函数会排在这个 Promise 对象的后面。</p>
<p>基本上，每一个 Promise 都代表了链中另一个异步过程的完成。</p>
<p>在过去，要想做多重的异步操作，会导致经典的回调地狱：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">doSomething</span>(<span class="keyword">function</span>(<span class="params">result</span>) &#123;</span><br><span class="line">  <span class="title function_">doSomethingElse</span>(result, <span class="keyword">function</span>(<span class="params">newResult</span>) &#123;</span><br><span class="line">    <span class="title function_">doThirdThing</span>(newResult, <span class="keyword">function</span>(<span class="params">finalResult</span>) &#123;</span><br><span class="line">      <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;Got the final result: &#x27;</span> + finalResult);</span><br><span class="line">    &#125;, failureCallback);</span><br><span class="line">  &#125;, failureCallback);</span><br><span class="line">&#125;, failureCallback);</span><br></pre></td></tr></table></figure>

<p>现在，我们可以把回调绑定到返回的 Promise 上，形成一个 Promise 链：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">doSomething</span>().<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">result</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="title function_">doSomethingElse</span>(result);</span><br><span class="line">&#125;)</span><br><span class="line">.<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">newResult</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="title function_">doThirdThing</span>(newResult);</span><br><span class="line">&#125;)</span><br><span class="line">.<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">finalResult</span>) &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;Got the final result: &#x27;</span> + finalResult);</span><br><span class="line">&#125;)</span><br><span class="line">.<span class="title function_">catch</span>(failureCallback);</span><br></pre></td></tr></table></figure>

<p>then 里的参数是可选的，<code>catch(failureCallback)</code> 是 <code>then(null, failureCallback)</code> 的缩略形式。如下所示，我们也可以用<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions">箭头函数</a>来表示：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">doSomething</span>()</span><br><span class="line">.<span class="title function_">then</span>(<span class="function"><span class="params">result</span> =&gt;</span> <span class="title function_">doSomethingElse</span>(result))</span><br><span class="line">.<span class="title function_">then</span>(<span class="function"><span class="params">newResult</span> =&gt;</span> <span class="title function_">doThirdThing</span>(newResult))</span><br><span class="line">.<span class="title function_">then</span>(<span class="function"><span class="params">finalResult</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">`Got the final result: <span class="subst">$&#123;finalResult&#125;</span>`</span>);</span><br><span class="line">&#125;)</span><br><span class="line">.<span class="title function_">catch</span>(failureCallback);</span><br></pre></td></tr></table></figure>

<p><strong>注意：</strong>一定要有返回值，否则，callback 将无法获取上一个 Promise 的结果。(如果使用箭头函数，<code>() =&gt; x</code> 比 <code>() =&gt; &#123; return x; &#125;</code> 更简洁一些，但后一种保留 <code>return</code> 的写法才支持使用多个语句。）。</p>
<h3 id="Catch的后续链式操作"><a href="#Catch的后续链式操作" class="headerlink" title="Catch的后续链式操作"></a>Catch的后续链式操作</h3><p>有可能会在一个回调失败之后继续使用链式操作，即，使用一个 <code>catch</code>，这对于在链式操作中抛出一个失败之后，再次进行新的操作会很有用。请阅读下面的例子：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;初始化&#x27;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="title function_">resolve</span>();</span><br><span class="line">&#125;)</span><br><span class="line">.<span class="title function_">then</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;有哪里不对了&#x27;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;执行「这个」”&#x27;</span>);</span><br><span class="line">&#125;)</span><br><span class="line">.<span class="title function_">catch</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;执行「那个」&#x27;</span>);</span><br><span class="line">&#125;)</span><br><span class="line">.<span class="title function_">then</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;执行「这个」，无论前面发生了什么&#x27;</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>输出结果如下：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">初始化</span><br><span class="line">执行“那个”</span><br><span class="line">执行“这个”，无论前面发生了什么</span><br></pre></td></tr></table></figure>

<p><strong>注意：</strong>因为抛出了错误 <strong>有哪里不对了</strong>，所以前一个 <strong>执行「这个」</strong> 没有被输出。</p>
<h2 id="错误传递-notebook"><a href="#错误传递-notebook" class="headerlink" title="错误传递:notebook:"></a>错误传递:notebook:</h2><p>在之前的回调地狱示例中，你可能记得有 3 次 <code>failureCallback</code> 的调用，而在 Promise 链中只有尾部的一次调用。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">doSomething</span>()</span><br><span class="line">.<span class="title function_">then</span>(<span class="function"><span class="params">result</span> =&gt;</span> <span class="title function_">doSomethingElse</span>(result))</span><br><span class="line">.<span class="title function_">then</span>(<span class="function"><span class="params">newResult</span> =&gt;</span> <span class="title function_">doThirdThing</span>(newResult))</span><br><span class="line">.<span class="title function_">then</span>(<span class="function"><span class="params">finalResult</span> =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">`Got the final result: <span class="subst">$&#123;finalResult&#125;</span>`</span>))</span><br><span class="line">.<span class="title function_">catch</span>(failureCallback);</span><br></pre></td></tr></table></figure>

<p>通常，一遇到异常抛出，浏览器就会顺着 Promise 链寻找下一个 <code>onRejected</code> 失败回调函数或者由 <code>.catch()</code> 指定的回调函数。这和以下同步代码的工作原理（执行过程）非常相似。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">  <span class="keyword">let</span> result = <span class="title function_">syncDoSomething</span>();</span><br><span class="line">  <span class="keyword">let</span> newResult = <span class="title function_">syncDoSomethingElse</span>(result);</span><br><span class="line">  <span class="keyword">let</span> finalResult = <span class="title function_">syncDoThirdThing</span>(newResult);</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">`Got the final result: <span class="subst">$&#123;finalResult&#125;</span>`</span>);</span><br><span class="line">&#125; <span class="keyword">catch</span>(error) &#123;</span><br><span class="line">  <span class="title function_">failureCallback</span>(error);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在 ECMAScript 2017 标准的 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function"><code>async/await</code></a> 语法糖中，这种异步代码的对称性得到了极致的体现：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">foo</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> result = <span class="keyword">await</span> <span class="title function_">doSomething</span>();</span><br><span class="line">    <span class="keyword">const</span> newResult = <span class="keyword">await</span> <span class="title function_">doSomethingElse</span>(result);</span><br><span class="line">    <span class="keyword">const</span> finalResult = <span class="keyword">await</span> <span class="title function_">doThirdThing</span>(newResult);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">`Got the final result: <span class="subst">$&#123;finalResult&#125;</span>`</span>);</span><br><span class="line">  &#125; <span class="keyword">catch</span>(error) &#123;</span><br><span class="line">    <span class="title function_">failureCallback</span>(error);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个例子是在 Promise 的基础上构建的，例如，<code>doSomething()</code> 与之前的函数是相同的。你可以在<a target="_blank" rel="noopener" href="https://developers.google.com/web/fundamentals/getting-started/primers/async-functions">这里</a>阅读更多的与此语法相关的文章。</p>
<p>通过捕获所有的错误，甚至抛出异常和程序错误，Promise 解决了回调地狱的基本缺陷。这对于构建异步操作的基础功能而言是很有必要的。</p>
<h2 id="Promise-拒绝事件"><a href="#Promise-拒绝事件" class="headerlink" title="Promise 拒绝事件"></a>Promise 拒绝事件</h2><p>当 Promise 被拒绝时，会有下文所述的两个事件之一被派发到全局作用域（通常而言，就是<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Window"><code>window</code></a>；如果是在 web worker 中使用的话，就是 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Worker"><code>Worker</code></a> 或者其他 worker-based 接口）。这两个事件如下所示：</p>
<ul>
<li><p><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Window/rejectionhandled_event"><code>rejectionhandled</code></a></p>
<p>当 Promise 被拒绝、并且在 <code>reject</code> 函数处理该 rejection 之后会派发此事件。</p>
</li>
<li><p><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Window/unhandledrejection_event"><code>unhandledrejection</code></a></p>
<p>当 Promise 被拒绝，但没有提供 <code>reject</code> 函数来处理该 rejection 时，会派发此事件。</p>
</li>
</ul>
<p>以上两种情况中，<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/PromiseRejectionEvent"><code>PromiseRejectionEvent</code></a> 事件都有两个属性，一个是 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/PromiseRejectionEvent/promise"><code>promise</code></a> 属性，该属性指向被驳回的 Promise，另一个是 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent/reason"><code>reason</code> (en-US)</a> 属性，该属性用来说明 Promise 被驳回的原因。</p>
<p>因此，我们可以通过以上事件为 Promise 失败时提供补偿处理，也有利于调试 Promise 相关的问题。<strong>在每一个上下文中，该处理都是全局的，因此不管源码如何，所有的错误都会在同一个处理函数中被捕捉并处理</strong>。</p>
<p>一个特别有用的例子：当你使用 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Glossary/Node.js">Node.js</a> 时，有些依赖模块可能会有未被处理的 rejected promises，这些都会在运行时打印到控制台。你可以在自己的代码中捕捉这些信息，然后添加与 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Window/unhandledrejection_event"><code>unhandledrejection</code></a> 相应的处理函数来做分析和处理，或只是为了让你的输出更整洁。举例如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable language_">window</span>.<span class="title function_">addEventListener</span>(<span class="string">&quot;unhandledrejection&quot;</span>, <span class="function"><span class="params">event</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">/* 你可以在这里添加一些代码，以便检查</span></span><br><span class="line"><span class="comment">     event.promise 中的 promise 和</span></span><br><span class="line"><span class="comment">     event.reason 中的 rejection 原因 */</span></span><br><span class="line"></span><br><span class="line">  event.<span class="title function_">preventDefault</span>();</span><br><span class="line">&#125;, <span class="literal">false</span>);</span><br></pre></td></tr></table></figure>

<p>调用 event 的 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Event/preventDefault"><code>preventDefault()</code></a> 方法是为了告诉 JavaScript 引擎当 Promise 被拒绝时不要执行默认操作，默认操作一般会包含把错误打印到控制台，Node 就是如此的。</p>
<p>理想情况下，在忽略这些事件之前，我们应该检查所有被拒绝的 Promise，来确认这不是代码中的 bug。</p>
<h2 id="在旧式回调-API-中创建-Promise"><a href="#在旧式回调-API-中创建-Promise" class="headerlink" title="在旧式回调 API 中创建 Promise"></a>在旧式回调 API 中创建 Promise</h2><p>可以通过 Promise 的构造器从零开始创建 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise"><code>Promise</code></a>。这种方式（通过构造器的方式）应当只在封装旧 API 的时候用到。</p>
<p>理想状态下，所有的异步函数都已经返回 Promise 了。但有一些 API 仍然使用旧方式来传入的成功（或者失败）的回调。典型的例子就是 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/en-US/docs/Web/API/setTimeout"><code>setTimeout()</code> (en-US)</a> 函数：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> <span class="title function_">saySomething</span>(<span class="string">&quot;10 seconds passed&quot;</span>), <span class="number">10000</span>);</span><br></pre></td></tr></table></figure>

<p>混用旧式回调和 Promise 可能会造成运行时序问题。如果 <code>saySomething</code> 函数失败了，或者包含了编程错误，那就没有办法捕获它了。这得怪 <code>setTimeout</code>。</p>
<p>幸运地是，我们可以用 Promise 来封装它。最好的做法是，将这些有问题的函数封装起来，留在底层，并且永远不要再直接调用它们：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">wait</span> = ms =&gt; <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> <span class="built_in">setTimeout</span>(resolve, ms));</span><br><span class="line"></span><br><span class="line"><span class="title function_">wait</span>(<span class="number">10000</span>).<span class="title function_">then</span>(<span class="function">() =&gt;</span> <span class="title function_">saySomething</span>(<span class="string">&quot;10 seconds&quot;</span>)).<span class="title function_">catch</span>(failureCallback);</span><br></pre></td></tr></table></figure>

<p>通常，Promise 的构造器接收一个执行函数 (executor)，我们可以在这个执行函数里手动地 resolve 和 reject 一个 Promise。既然 <code>setTimeout</code> 并不会真的执行失败，那么我们可以在这种情况下忽略 reject。</p>
<h2 id="组合-notebook"><a href="#组合-notebook" class="headerlink" title="组合:notebook:"></a>组合:notebook:</h2><p><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve"><code>Promise.resolve()</code></a> 和 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject"><code>Promise.reject()</code></a> 是手动创建一个已经 resolve 或者 reject 的 Promise 快捷方法。它们有时很有用。</p>
<p><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all"><code>Promise.all()</code></a> 和 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/race"><code>Promise.race()</code></a> 是并行运行异步操作的两个组合式工具。</p>
<p>我们可以发起并行操作，然后等多个操作全部结束后进行下一步操作，如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">Promise</span>.<span class="title function_">all</span>([<span class="title function_">func1</span>(), <span class="title function_">func2</span>(), <span class="title function_">func3</span>()])</span><br><span class="line">.<span class="title function_">then</span>(<span class="function">(<span class="params">[result1, result2, result3]</span>) =&gt;</span> &#123; <span class="comment">/* use result1, result2 and result3 */</span> &#125;);</span><br></pre></td></tr></table></figure>

<p>可以使用一些聪明的 JavaScript 写法实现时序组合：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[func1, func2, func3].<span class="title function_">reduce</span>(<span class="function">(<span class="params">p, f</span>) =&gt;</span> p.<span class="title function_">then</span>(f), <span class="title class_">Promise</span>.<span class="title function_">resolve</span>())</span><br><span class="line">.<span class="title function_">then</span>(<span class="function"><span class="params">result3</span> =&gt;</span> &#123; <span class="comment">/* use result3 */</span> &#125;);</span><br></pre></td></tr></table></figure>

<p>通常，我们递归调用一个由异步函数组成的数组时，相当于一个 Promise 链：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">Promise</span>.<span class="title function_">resolve</span>().<span class="title function_">then</span>(func1).<span class="title function_">then</span>(func2).<span class="title function_">then</span>(func3);</span><br></pre></td></tr></table></figure>

<p>我们也可以写成可复用的函数形式，这在函数式编程中极为普遍：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">applyAsync</span> = (<span class="params">acc,val</span>) =&gt; acc.<span class="title function_">then</span>(val);</span><br><span class="line"><span class="keyword">const</span> <span class="title function_">composeAsync</span> = (<span class="params">...funcs</span>) =&gt; <span class="function"><span class="params">x</span> =&gt;</span> funcs.<span class="title function_">reduce</span>(applyAsync, <span class="title class_">Promise</span>.<span class="title function_">resolve</span>(x));</span><br></pre></td></tr></table></figure>

<p><code>composeAsync()</code> 函数将会接受任意数量的函数作为其参数，并返回一个新的函数，该函数接受一个通过 composition pipeline 传入的初始值。这对我们来说非常有益，因为任一函数可以是异步或同步的，它们能被保证按顺序执行：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> transformData = <span class="title function_">composeAsync</span>(func1, func2, func3);</span><br><span class="line"><span class="keyword">const</span> result3 = <span class="title function_">transformData</span>(data);</span><br></pre></td></tr></table></figure>

<p>在 ECMAScript 2017 标准中，时序组合可以通过使用 <code>async/await</code> 而变得更简单：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> result;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">const</span> f <span class="keyword">of</span> [func1, func2, func3]) &#123;</span><br><span class="line">  result = <span class="keyword">await</span> <span class="title function_">f</span>(result);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* use last result (i.e. result3) */</span></span><br></pre></td></tr></table></figure>

<h2 id="时序-notebook"><a href="#时序-notebook" class="headerlink" title="时序:notebook:"></a>时序:notebook:</h2><p>为了避免意外，即使是一个已经变成 resolve 状态的 Promise，传递给 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/then"><code>then()</code></a> 的函数也总是会被异步调用：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">Promise</span>.<span class="title function_">resolve</span>().<span class="title function_">then</span>(<span class="function">() =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">2</span>));</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">1</span>); <span class="comment">// 1, 2</span></span><br></pre></td></tr></table></figure>

<p><strong>传递到 <code>then()</code> 中的函数被置入到一个微任务队列中，而不是立即执行，这意味着它是在 JavaScript 事件队列的所有运行时结束了，且事件队列被清空之后，才开始执行</strong>：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">wait</span> = ms =&gt; <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> <span class="built_in">setTimeout</span>(resolve, ms));</span><br><span class="line"></span><br><span class="line"><span class="title function_">wait</span>().<span class="title function_">then</span>(<span class="function">() =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">4</span>));</span><br><span class="line"><span class="title class_">Promise</span>.<span class="title function_">resolve</span>().<span class="title function_">then</span>(<span class="function">() =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">2</span>)).<span class="title function_">then</span>(<span class="function">() =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">3</span>));</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">1</span>); <span class="comment">// 1, 2, 3, 4</span></span><br></pre></td></tr></table></figure>

<h2 id="嵌套-notebook"><a href="#嵌套-notebook" class="headerlink" title="嵌套:notebook:"></a>嵌套:notebook:</h2><p>简便的 Promise 链式编程最好保持扁平化，不要嵌套 Promise，因为嵌套经常会是粗心导致的。可查阅下一节的<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Using_promises#%E5%B8%B8%E8%A7%81%E9%94%99%E8%AF%AF">常见错误</a>中的例子。</p>
<p>嵌套 Promise 是一种可以限制 <code>catch</code> 语句的作用域的控制结构写法。明确来说，嵌套的 <code>catch</code> 仅捕捉在其之前同时还必须是其作用域的 failureres，而捕捉不到在其链式以外或者其嵌套域以外的 error。如果使用正确，那么可以实现高精度的错误修复。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">doSomethingCritical</span>()</span><br><span class="line">.<span class="title function_">then</span>(<span class="function"><span class="params">result</span> =&gt;</span> <span class="title function_">doSomethingOptional</span>()</span><br><span class="line">  .<span class="title function_">then</span>(<span class="function"><span class="params">optionalResult</span> =&gt;</span> <span class="title function_">doSomethingExtraNice</span>(optionalResult))</span><br><span class="line">  .<span class="title function_">catch</span>(<span class="function"><span class="params">e</span> =&gt;</span> &#123;<span class="variable language_">console</span>.<span class="title function_">log</span>(e.<span class="property">message</span>)&#125;)) <span class="comment">// 即使有异常也会忽略，继续运行;(最后会输出)</span></span><br><span class="line">.<span class="title function_">then</span>(<span class="function">() =&gt;</span> <span class="title function_">moreCriticalStuff</span>())</span><br><span class="line">.<span class="title function_">catch</span>(<span class="function"><span class="params">e</span> =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;Critical failure: &quot;</span> + e.<span class="property">message</span>));<span class="comment">// 没有输出</span></span><br></pre></td></tr></table></figure>

<p>注意，有些代码步骤是嵌套的，而不是一个简单的纯链式，这些语句前与后都被括号 <code>()</code> 包裹着。</p>
<p>这个内部的 <code>catch</code> 语句仅能捕获到 <code>doSomethingOptional()</code> 和 <code>doSomethingExtraNice()</code> 的失败，<code>之后就恢复到 moreCriticalStuff()</code> 的运行。重要提醒：如果 <code>doSomethingCritical()</code> 失败，这个错误仅会被最后的（外部）<code>catch</code> 语句捕获到。</p>
<h2 id="常见错误"><a href="#常见错误" class="headerlink" title="常见错误"></a>常见错误</h2><p>在编写 Promise 链时，需要注意以下示例中展示的几个错误：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 错误示例，包含 3 个问题！</span></span><br><span class="line"><span class="title function_">doSomething</span>().<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">result</span>) &#123;</span><br><span class="line">  <span class="title function_">doSomethingElse</span>(result) <span class="comment">// 没有返回 Promise 以及没有必要的嵌套 Promise</span></span><br><span class="line">  .<span class="title function_">then</span>(<span class="function"><span class="params">newResult</span> =&gt;</span> <span class="title function_">doThirdThing</span>(newResult));</span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="function">() =&gt;</span> <span class="title function_">doFourthThing</span>());</span><br><span class="line"><span class="comment">// 最后，是没有使用 catch 终止 Promise 调用链，可能导致没有捕获的异常</span></span><br></pre></td></tr></table></figure>

<p>第一个错误是没有正确地将事物相连接。当我们创建新 Promise 但忘记返回它时，会发生这种情况。因此，链条被打破，或者更确切地说，我们有两个独立的链条竞争（同时在执行两个异步而非一个一个的执行）。这意味着 <code>doFourthThing()</code> 不会等待 <code>doSomethingElse()</code> 或 <code>doThirdThing()</code> 完成，并且将与它们并行运行，可能是无意的。单独的链也有单独的错误处理，导致未捕获的错误。</p>
<p>第二个错误是不必要地嵌套，实现第一个错误。嵌套还限制了内部错误处理程序的范围，如果是非预期的，可能会导致未捕获的错误。其中一个变体是 <a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it">Promise 构造函数反模式</a>，它结合了 Promise 构造函数的多余使用和嵌套。</p>
<p>第三个错误是忘记用 <code>catch</code> 终止链。这导致在大多数浏览器中不能终止的 Promise 链里的 rejection。</p>
<p>一个好的经验法则是总是返回或终止 Promise 链，并且一旦你得到一个新的 Promise，返回它。下面是修改后的平面化的代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">doSomething</span>()</span><br><span class="line">.<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">result</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="title function_">doSomethingElse</span>(result);</span><br><span class="line">&#125;)</span><br><span class="line">.<span class="title function_">then</span>(<span class="function"><span class="params">newResult</span> =&gt;</span> <span class="title function_">doThirdThing</span>(newResult))</span><br><span class="line">.<span class="title function_">then</span>(<span class="function">() =&gt;</span> <span class="title function_">doFourthThing</span>())</span><br><span class="line">.<span class="title function_">catch</span>(<span class="function"><span class="params">error</span> =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(error));</span><br></pre></td></tr></table></figure>

<p>注意：<code>() =&gt; x</code> 是 <code>() =&gt; &#123; return x; &#125;</code> 的简写。</p>
<p>上述代码的写法就是具有适当错误处理的简单明确的链式写法。</p>
<p>使用 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function">async&#x2F;await</a> 可以解决以上大多数错误，使用 <code>async/await</code> 时，最常见的语法错误就是忘记了 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/await"><code>await</code></a> 关键字。</p>
<h2 id="参见"><a href="#参见" class="headerlink" title="参见"></a><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Using_promises#%E5%8F%82%E8%A7%81">参见</a></h2><ul>
<li><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/then"><code>Promise.then()</code></a></li>
<li><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function"><code>async</code>&#x2F;<code>await</code></a></li>
<li><a target="_blank" rel="noopener" href="https://promisesaplus.com/">Promises&#x2F;A+ specification</a></li>
<li><a target="_blank" rel="noopener" href="https://medium.com/@ramsunvtech/promises-of-promise-part-1-53f769245a53">Venkatraman.R - JS Promise (Part 1, Basics)</a></li>
<li><a target="_blank" rel="noopener" href="https://medium.com/@ramsunvtech/js-promise-part-2-q-js-when-js-and-rsvp-js-af596232525c">Venkatraman.R - JS Promise (Part 2 - Using Q.js, When.js and RSVP.js)</a></li>
<li><a target="_blank" rel="noopener" href="https://tech.io/playgrounds/11107/tools-for-promises-unittesting/introduction">Venkatraman.R - Tools for Promises Unit Testing</a></li>
<li><a target="_blank" rel="noopener" href="https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html">Nolan Lawson: We have a problem with promises — Common mistakes with promises</a></li>
</ul>
<hr>

        
            <div class="donate-container">
    <div class="donate-button">
        <button id="donate-button">赞赏</button>
    </div>
    <div class="donate-img-container hide" id="donate-img-container">
        <img id="donate-img" src="" data-src="/myblog/img/donate.jpg">
        <p> 感谢鼓励 </p>
    </div>
</div>
        
        <br />
        <div id="comment-container">
        </div>
        <div id="disqus_thread"></div>
        <div id="lv-container"></div>
        <div class="giscus"></div>
    </div>
</div>

    </div>
</div>


<footer class="footer">
    <ul class="list-inline text-center">
        
        

        

        

        
        <li>
            <a target="_blank"  href="https://github.com/samuel-24276">
                            <span class="fa-stack fa-lg">
                                <i class="iconfont icon-github"></i>
                            </span>
            </a>
        </li>
        

        

    </ul>
    
    <p>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://github.com/samuel-24276">samuel-24276&#39;s Page</a></span>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/">北京-未备案</a></span>
        <span>/</span>
        
        <span><a href="#">返回顶部</a></span>
        <span>/</span>
        
    </p>
    
    <p>
        <span id="busuanzi_container_site_pv">
            <span id="busuanzi_value_site_pv"></span>PV
        </span>
        <span id="busuanzi_container_site_uv">
            <span id="busuanzi_value_site_uv"></span>UV
        </span>
        Created By <a target="_blank" rel="noopener" href="https://hexo.io/">Hexo</a>  Theme <a target="_blank" rel="noopener" href="https://github.com/aircloud/hexo-theme-aircloud">AirCloud</a></p>
</footer>




</body>

<script>
    // We expose some of the variables needed by the front end
    window.hexo_search_path = "search.json"
    window.hexo_root = "/myblog/"
    window.isPost = true
</script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

<script src="/myblog/js/index.js"></script>

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>






    <script type="text/javascript">
       (function() {
           if (typeof LivereTower === 'function') { return; }

           var j, d = document.getElementById('lv-container');

           d.setAttribute('data-id','city');
           d.setAttribute('data-uid' , 'MTAyMC80OTA5OC8yNTU5Mw==');

           j = document.createElement('script');
           j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
           j.async = true;

           d.appendChild(j);
       })();
    </script>
    <noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
    </div>

</html>
